package com.bsoft.gol.hbs.utils;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

public class JsapiTicketUtil {

    private static final Logger log = LoggerFactory.getLogger(JsapiTicketUtil.class);

    /**
     * * 模拟get请求
     *
     * @param url
     * @param charset
     * @param timeout
     * @return
     */
    public static String sendGet(String url, String charset, int timeout) {
        String result = "";
        try {
            URL u = new URL(url);
            try {
                URLConnection conn = u.openConnection();
                conn.connect();
                conn.setConnectTimeout(timeout);
                BufferedReader in =
                        new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
                String line = "";
                while ((line = in.readLine()) != null) {

                    result = result + line;
                }
                in.close();
            } catch (IOException e) {
                return result;
            }
        } catch (MalformedURLException e) {
            return result;
        }

        return result;
    }

    /**
     * @description: 获取acess_token
     * @author: chenJij@bsoft.com.cn
     * @date: 2019/11/20 13:17
     * @param: appid  应用ID
     * @param: appSecret  (应用密钥)
     * @return:
     */
    public static String getAccessToken(String appid, String appSecret) {
        String url =
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                        + appid
                        + "&secret="
                        + appSecret;
        log.info("url :{}",url);
        String backData = sendGet(url, "utf-8", 10000);
        log.info("backData :{}",backData);
        String accessToken = (String) ((Map)JSONObject.parse(backData)).get("access_token");
        return accessToken;
    }
}
